package com.im.app.manager;

import com.alibaba.fastjson.JSONObject;
import com.im.app.model.Conversations;
import com.im.app.model.User;
import com.im.app.utils.uuid.IdUtils;
import org.jim.core.ImPacket;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.config.ImConfig;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.ChatType;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.util.ChatKit;

import java.util.*;

public class ConversationManager {

    private static ConversationManager manager;

    public ConversationManager(){

    }

    public Set<String> customerUsers = new HashSet<>(); //用户
    public Set<String> serverUsers = new HashSet<>(); //客服

    public Map<String,Conversations> userConversation = new HashMap<>();
    public Map<String, List<Conversations>> groupConversation = new HashMap<>();

    public static ConversationManager getManager(){
        if(manager == null){
            synchronized (ConversationManager.class){
                if(manager == null){
                    manager = new ConversationManager();
                }
            }
        }
        return manager;
    }

    public void cacheGroupConversations(String key,List<Conversations> conversations){
        groupConversation.put(key,conversations);
    }

    public List<Conversations> getGroupConversations(String key){
        List<Conversations> conversations = groupConversation.get(key);
        if (conversations == null){
            conversations = getRedisGroupConversation(key);
        }
        return conversations;
    }

    public void delCacheConversation(Conversations conversations){
        String key = "";
        if(conversations.getConversationType() == ChatType.CHAT_TYPE_PUBLIC.getNumber()){
            key  = "conversation_"+conversations.getOwnerUserId()+"_"+conversations.getGroupId();
        }else {
            key  = "conversation_"+conversations.getOwnerUserId()+"_"+conversations.getUserId();
        }
        ConversationManager.getManager().removeConversation(key);
        try {
            JedisTemplate.me().delKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void cacheGroupConversation(List<Conversations> conversations,String groupId){
        if(conversations == null) return;
        String key = "conversation_"+groupId;
        ConversationManager.getManager().cacheGroupConversations(key,conversations);
        try {
            JedisTemplate.me().set(key,conversations);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delCacheGroupConversation(String groupId){
        String key = "conversation_"+groupId;
        ConversationManager.getManager().removeGroupConversation(key);
        try {
            JedisTemplate.me().delKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void removeGroupConversation(String key){
        groupConversation.remove(key);
    }

    public List<Conversations> getRedisGroupConversation(String key){
        List<Conversations> conversations = new ArrayList<>();
        try {
            List<JSONObject> list = JedisTemplate.me().get(key, List.class);
            for (JSONObject obj: list) {
                Conversations conversations1 = obj.toJavaObject(Conversations.class);
                conversations.add(conversations1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conversations;
    }

    public Conversations getRedisConversation(String key){
        Conversations conversations = null;
        try {
            conversations = JedisTemplate.me().get(key, Conversations.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conversations;
    }

    public void cacheConversation(Conversations conversations){
        if(conversations == null) return;
        String key = "";
        if(conversations.getConversationType() == ChatType.CHAT_TYPE_PUBLIC.getNumber()){
            key  = "conversation_"+conversations.getOwnerUserId()+"_"+conversations.getGroupId();
        }else {
            key  = "conversation_"+conversations.getOwnerUserId()+"_"+conversations.getUserId();
        }
        cacheConversation(key,conversations);
        try {
            JedisTemplate.me().set(key,conversations,60*60*24 * 7);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cacheConversation(String key,Conversations conversation){
        userConversation.put(key,conversation);
    }

    public Conversations getConversation(String key){
        Conversations conversations = userConversation.get(key);
        if (conversations == null){
            conversations = getRedisConversation(key);
        }
        return conversations;
    }

    public void removeConversation(String key){
        userConversation.remove(key);
    }


    public void sendUserChange(Conversations conversations){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(conversations.getOwnerUserId(),isStore)){
            conversations.setOnLine(ChatKit.isOnline(conversations.getUserId(),isStore));
            ImPacket imPacket = new ImPacket(Command.COMMAND_CHANGE_CONVERSATION_RESP,new RespBody(Command.COMMAND_CHANGE_CONVERSATION_RESP,conversations).toByte());
            JimServerAPI.sendToUser(conversations.getOwnerUserId(),imPacket);
        }
    }

    public void sendUserNew(Conversations conversations){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(conversations.getOwnerUserId(),isStore)){
            ImPacket imPacket = new ImPacket(Command.COMMAND_NEW_CONVERSATION_RESP,new RespBody(Command.COMMAND_NEW_CONVERSATION_RESP,conversations).toByte());
            JimServerAPI.sendToUser(conversations.getOwnerUserId(),imPacket);
        }
    }

    public void sendGroupChange(Conversations conversations){
        ImServerConfig imServerConfig = ImConfig.Global.get();
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(ChatKit.isOnline(conversations.getOwnerUserId(),isStore)){
            ImPacket imPacket = new ImPacket(Command.COMMAND_CHANGE_CONVERSATION_RESP,new RespBody(Command.COMMAND_CHANGE_CONVERSATION_RESP,conversations).toByte());
            JimServerAPI.sendToGroup(conversations.getGroupId(),imPacket);
        }
    }

    public void sendUserOnLine(String toUserId, String userId){
        //发送系统消息给客服
        RespBody body = new RespBody();
        body.setCommand(Command.COMMAND_FRIEND_ONLINE_RESP);
        body.setData(userId);
        body.setMsg("好友上线提醒");
        ImPacket chatPacket = new ImPacket(Command.COMMAND_FRIEND_ONLINE_RESP,body.toByte());
        JimServerAPI.sendToUser(toUserId,chatPacket);
    }

    public void sendUserOffLine(String toUserId, String userId){
        //发送系统消息给客服
        RespBody body = new RespBody();
        body.setCommand(Command.COMMAND_FRIEND_OFFLINE_RESP);
        body.setData(userId);
        body.setMsg("好友离线提醒");
        ImPacket chatPacket = new ImPacket(Command.COMMAND_FRIEND_OFFLINE_RESP,body.toByte());
        JimServerAPI.sendToUser(toUserId,chatPacket);
    }

    public Conversations createConversation(ChatBody body,String userId,String name,String avatar,Integer readCount){
        String json = JsonKit.toJSONString(body);
        Conversations conversation = new Conversations();
        conversation.setConversationType(body.getChatType());
        conversation.setConversationId(IdUtils.simpleUUID());
        conversation.setOwnerUserId(userId);
        conversation.setUserId(body.getFrom());
        conversation.setLastMessageId(body.getId());
        conversation.setLastMessage(json);
        conversation.setLastTime(new Date().getTime());
        conversation.setIsPinned(0);
        conversation.setIsBlack(0);
        conversation.setNickName(name);
        conversation.setAvatar(avatar);
        conversation.setUnreadCount(readCount);
        sendUserChange(conversation);
        return conversation;
    }

    public void addServerUser(String userId){
        this.serverUsers.add(userId);
    }

    public void removeServerUser(String userId){
        this.serverUsers.remove(userId);
    }

    public void addCustomerUser(String userId){
        this.customerUsers.add(userId);
    }

    public void removeCustomerUser(String userId){
        this.customerUsers.remove(userId);
    }

    //总用户数
    public int totalUser(){
        return this.customerUsers.size() + this.serverUsers.size();
    }

}
